package com.td.filemanager.provider;

import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.app.Context;

import java.util.List;

/**
 * 列表组件提供者
 */
public abstract class ListComponentProvider<T> extends BaseItemProvider {
    private Context mContext;
    private List<T> mList;
    private int mResourceId;

    private OnItemClickListener<T> mOnItemClickListener;

    /**
     * 列表组件提供者构造方法
     *
     * @param context 上下文对象
     * @param mList 列表
     * @param resourceId 资源id
     */
    public ListComponentProvider(Context context, List<T> mList, int resourceId) {
        this.mContext = context;
        this.mList = mList;
        this.mResourceId = resourceId;
    }

    /**
     * 列表项绑定抽象方法
     *
     * @param componentViewHolder componentViewHolder
     * @param item 数据项
     * @param position 位置
     */
    protected abstract void onItemDataBind(ComponentViewHolder componentViewHolder, T item, int position);

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public T getItem(int index) {
        return mList.get(index);
    }

    @Override
    public long getItemId(int index) {
        return index;
    }

    @Override
    public Component getComponent(int index, Component component, ComponentContainer componentContainer) {
        ComponentViewHolder viewHolder;
        if (component == null) {
            component = LayoutScatter.getInstance(mContext).parse(mResourceId, null, false);
            viewHolder = new ComponentViewHolder(component);
            component.setTag(viewHolder);
        } else {
            viewHolder = (ComponentViewHolder) component.getTag();
        }
        if (viewHolder != null) {
            T item = mList.get(index);
            onItemDataBind(viewHolder, item, index);
            viewHolder.getComponentView().setClickedListener(componentView -> {
                if (mOnItemClickListener != null) {
                    mOnItemClickListener.onItemClick(componentView, item, index);
                }
            });
        }
        return component;
    }

    /**
     * 设置点击回调
     * @param onItemClickListener 点击回调
     */
    public void setOnItemClickListener(OnItemClickListener<T> onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    /**
     * 点击监听接口
     *
     * @param <T> 泛型
     */
    public interface OnItemClickListener<T> {
        void onItemClick(Component component, T item, int position);
    }
}
